package com.cheetah.start.common.interceptor;

import com.cheetah.start.common.annotation.NeedLogin;
import com.cheetah.start.common.constant.SessionConst;
import com.cheetah.start.system.admin.domain.SysAdmin;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author Feel
 * @create 2021/7/18
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
        SysAdmin admin = (SysAdmin) request.getSession().getAttribute(SessionConst.NAME);
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取方法上注解
        Method method = handlerMethod.getMethod();
        NeedLogin annotation = method.getAnnotation(NeedLogin.class);
        // 获取类上注解
        NeedLogin classAnno = method.getDeclaringClass().getAnnotation(NeedLogin.class);
        if (annotation == null && classAnno == null) {
            return true;
        } else {
            if (admin == null) {
                request.getRequestDispatcher("/jumpLogin").forward(request, response);
                return false;
            } else {
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  {

    }
}
